package com.solution.admin.auth.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.solution.admin.auth.constants.AuthConstants;
import com.solution.admin.auth.entity.ResourceEntity;
import com.solution.admin.auth.entity.TodoEntity;
import com.solution.admin.auth.security.UsernamePasswordToken;
import com.solution.admin.auth.service.ResourceService;
import com.solution.admin.auth.service.RoleService;
import com.solution.admin.auth.service.UserService;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.home.service.IndexService;
import com.solution.admin.settings.entity.DictVO;
import com.solution.admin.settings.entity.KeyMapEntity;
import com.solution.admin.settings.service.KeyMapService;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.UserPrincipal;
import com.solution.common.utils.string.StringUtil;

/**
 * 用户登录web层
 * @author llp
 * @version 2017/3/23
 */
@Controller
public class LoginController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(LoginController.class);

	/** 获取用户基本信息接口 */
	@Autowired
	private UserService userService;

	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private IndexService indexService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private KeyMapService keyMapService;

	/**
	 * 登录
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse res) {
		Map<String, Object> returnMap = new HashMap<String, Object>();
		HttpServletResponse response = (HttpServletResponse) res;
		// 用户名
		String userName = request.getParameter("username");
		// 密码
		String password = request.getParameter("password");
		// 记住密码
		if (null == userName || null == password) {
			return "redirect:/login.jsp";
		}
		// 当前用户
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken();
		token.setUsername(userName);
		token.setPassword(password.toCharArray());
		currentUser.login(token);
		List<ResourceEntity> userMenuList = this.resourceService.getUserMenuList(getUserId());
		request.setAttribute("currUserName", this.getUserName());
		int userMenuListSize=0;
		if(userMenuList!=null){
			userMenuListSize=userMenuList.size();
		}
		request.setAttribute("userMenuList", userMenuList);
		request.setAttribute("userMenuListSize", userMenuListSize);
		request.setAttribute("userType", this.getUserType());
		
		// 生成之前将所有字典生成json 数据，传到页面，表格和查询条件中的字典项，统一在前端进行渲染
		request.setAttribute("dictMap", initAllDict());
		
		return "main";
	}
	
	/**
	 * 直接进入主页页面
	 * @param request
	 * @param re
	 * @return
	 */
	@RequestMapping("/entry")
	public String directEntryIndex(HttpServletRequest request, HttpServletResponse re) {
		List<ResourceEntity> userMenuList = this.resourceService.getUserMenuList(getUserId());
		request.setAttribute("currUserName", this.getUserName());
		int userMenuListSize = 0;
		if (userMenuList != null) {
			userMenuListSize = userMenuList.size();
		}
		request.setAttribute("userMenuList", userMenuList);
		request.setAttribute("userMenuListSize", userMenuListSize);
		request.setAttribute("userType", this.getUserType());
		UserPrincipal user = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
		// 待办事项
		Long salesmanRoleId = null;
		// 默认是业务员，看不到待办事项
		request.setAttribute("isSalesman", 1);
		// 业务员的角色ID
		List<KeyMapEntity> keyList = keyMapService.listKeyMap("salesmanRoleId");
		if (null != keyList && keyList.size() > 0) {
			salesmanRoleId = Long.parseLong(keyList.get(0).getKeyValue());
			if (null != salesmanRoleId && !roleService.checkUserRoleChkFlg(user.getId(), salesmanRoleId)) {
				request.setAttribute("isSalesman", 0);
				// 查询待办事项数量
				Map<String, Object> tparam = new HashMap<>();
				List<TodoEntity> todoList = indexService.listTodoList(tparam);
				if (todoList != null && todoList.size() > 0) {
					for (TodoEntity todo : todoList) {
						request.setAttribute(todo.getTodoName(), todo.getTodoNum());
					}
				}
			} else {
				request.setAttribute("isSalesman", 1);
			}
		}
		// 生成之前将所有字典生成json 数据，传到页面，表格和查询条件中的字典项，统一在前端进行渲染
		request.setAttribute("dictMap", initAllDict());
		return "main";
	}

	/**
	 * 初始化所有字典项
	 * @return
	 */
	private String initAllDict(){
		List<KeyMapEntity> keyList = keyMapService.listAllDict();
		Map<String, List<DictVO>> resultMap = new HashMap<String, List<DictVO>>();
		if(keyList != null && keyList.size() > 0){
			for (KeyMapEntity keyMap : keyList) {
				if(StringUtil.isNotEmpty(keyMap.getDictListStr())){
					List<KeyMapEntity> dictList = JSONArray.parseArray("["+keyMap.getDictListStr()+"]", KeyMapEntity.class);
					resultMap.put(keyMap.getKeyType(),convertDictVO(dictList));
				}
			}
		}
		return JSON.toJSONString(resultMap);
	}
	
	/**
	 * 转化字典项到DictVO
	 * @param kmList
	 * @return
	 */
	private List<DictVO> convertDictVO(List<KeyMapEntity> kmList){
		List<DictVO> dictVoList = new ArrayList<DictVO>();
		if(kmList != null && kmList.size() > 0){
			for (KeyMapEntity km : kmList) {
				DictVO dv = new DictVO(km.getKeyValue(), km.getKeyIntro());
				dictVoList.add(dv);
			}
		}
		return dictVoList;
	}
	

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse res) {
		// 当前用户
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "redirect:/login.jsp";
	}

	
	@RequestMapping("/pc/logout")
	public String pclogout(HttpServletRequest request, HttpServletResponse res) {
		// 当前用户
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		return "redirect:/page/pc/login/login.jsp";
	}
	
	
	@ExceptionHandler({ Exception.class })
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException ex) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("ex", ex);
		mv.setViewName("error/403");
		return mv;
	}
	
	/**
	 * shiro无授权时根据终端跳转登录页面
	 * @param request
	 * @return
	 * @author llp
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/redirectLoginUrl")
	public String loginHandler(HttpServletRequest request){
		// 从Redis中取终端访问标识
		ServletContext sc = request.getSession().getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
        RedisTemplate template = (RedisTemplate)cxt.getBean("redisTemplate");
        BoundValueOperations options = template.boundValueOps("LOGIN_TERMINAL_"+request.getSession().getId().substring(12));
		String loginTerminalType = (String)options.get();
		if(AuthConstants.LOGIN_TERMINAL_TYPE.WX.getCode().equals(loginTerminalType)){
			return "redirect:/wx/my/toBindAccountPage";
			//return "redirect:/login.jsp";
		}else if(AuthConstants.LOGIN_TERMINAL_TYPE.PC.getCode().equals(loginTerminalType)){
			return "redirect:/home/loginPage";
		}else{
			return "redirect:/login.jsp";
		}
	}

	/**
	 * 登陆成功后跳转页面
	 * 
	 * @return
	 * @author qiaoenyin
	 * @date 2017年4月18日 上午11:49:01
	 */
	@RequestMapping("success")
	public String success() {
		return "product/category";
	}

}
